/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.locationarea.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.locationarea.entity.BizLocationArea;
import vip.xiaonuo.biz.modular.locationarea.mapper.BizLocationAreaMapper;
import vip.xiaonuo.biz.modular.locationarea.param.*;
import vip.xiaonuo.biz.modular.locationarea.service.BizLocationAreaService;
import vip.xiaonuo.biz.modular.locationarea.vo.BizLocationAreaResp;
import vip.xiaonuo.biz.modular.relation.entity.BizRelation;
import vip.xiaonuo.biz.modular.relation.enums.BizRelationCategoryEnum;
import vip.xiaonuo.biz.modular.relation.service.BizRelationService;
import vip.xiaonuo.common.enums.CommonDeleteFlagEnum;
import vip.xiaonuo.common.exception.CommonException;

import java.util.List;

/**
 * 区域Service接口实现类
 *
 * @author kongxm
 * @date 2022/11/06 21:00
 **/
@Service
public class BizLocationAreaServiceImpl extends ServiceImpl<BizLocationAreaMapper, BizLocationArea> implements BizLocationAreaService {
    @Autowired
    private BizRelationService bizRelationService;

    @Override
    public Page<BizLocationAreaResp> page(BizLocationAreaPageParam bizLocationAreaPageParam) {
        return getBaseMapper()
                .page(Page.of(bizLocationAreaPageParam.getCurrent(), bizLocationAreaPageParam.getSize()),
                        bizLocationAreaPageParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(BizLocationAreaAddParam bizLocationAreaAddParam) {
        // It can't be executed if there already exist a same name or a same code.
        long existSameCodeCount = count(new LambdaQueryWrapper<BizLocationArea>()
                .eq(BizLocationArea::getCode, bizLocationAreaAddParam.getCode()));
        Assert.isTrue(existSameCodeCount == 0, "编号{}已存在", bizLocationAreaAddParam.getCode());

        long existSameNameCount = count(new LambdaQueryWrapper<BizLocationArea>()
                .eq(BizLocationArea::getName, bizLocationAreaAddParam.getName()));
        Assert.isTrue(existSameNameCount == 0, "名称{}已存在", bizLocationAreaAddParam.getName());

        BizLocationArea bizLocationArea = BeanUtil.toBean(bizLocationAreaAddParam, BizLocationArea.class);
        this.save(bizLocationArea);
        bizRelationService.saveRelationWithClear(bizLocationArea.getId(),
                bizLocationAreaAddParam.getUserId(),
                BizRelationCategoryEnum.BIZ_RELATION_AREA_USER_IN_CHARGE.getValue());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(BizLocationAreaEditParam bizLocationAreaEditParam) {
        // It can't be executed if there already exist a same name or a same code.
        long existSameCodeCount = count(new LambdaQueryWrapper<BizLocationArea>()
                .eq(BizLocationArea::getCode, bizLocationAreaEditParam.getCode())
                .ne(BizLocationArea::getId, bizLocationAreaEditParam.getId()));
        Assert.isTrue(existSameCodeCount == 0, "编号{}已存在", bizLocationAreaEditParam.getCode());

        long existSameNameCount = count(new LambdaQueryWrapper<BizLocationArea>()
                .eq(BizLocationArea::getName, bizLocationAreaEditParam.getName())
                .ne(BizLocationArea::getId, bizLocationAreaEditParam.getId()));
        Assert.isTrue(existSameNameCount == 0, "名称{}已存在", bizLocationAreaEditParam.getName());

        BizLocationArea bizLocationArea = this.queryEntity(bizLocationAreaEditParam.getId());
        BeanUtil.copyProperties(bizLocationAreaEditParam, bizLocationArea);
        this.updateById(bizLocationArea);
        bizRelationService.saveRelationWithClear(bizLocationArea.getId(),
                bizLocationAreaEditParam.getUserId(),
                BizRelationCategoryEnum.BIZ_RELATION_AREA_USER_IN_CHARGE.getValue());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizLocationAreaIdParam> bizLocationAreaIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(bizLocationAreaIdParamList, BizLocationAreaIdParam::getId));
        bizLocationAreaIdParamList.forEach(item -> bizRelationService.remove(new LambdaQueryWrapper<BizRelation>()
                .eq(BizRelation::getObjectId, item.getId())));
    }

    @Override
    public BizLocationArea detail(BizLocationAreaIdParam bizLocationAreaIdParam) {
        return this.queryEntity(bizLocationAreaIdParam.getId());
    }

    @Override
    public BizLocationArea queryEntity(String id) {
        BizLocationArea bizLocationArea = this.getById(id);
        if (ObjectUtil.isEmpty(bizLocationArea)) {
            throw new CommonException("区域不存在，id值为：{}", id);
        }
        return bizLocationArea;
    }

    @Override
    public List<BizLocationArea> list(BizLocationAreaListParam bizLocationAreaListParam) {
        BizLocationArea bizLocationArea = BeanUtil.copyProperties(bizLocationAreaListParam, BizLocationArea.class);
        return list(new LambdaQueryWrapper<>(bizLocationArea)
                .eq(BizLocationArea::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE));
    }
}
